package com.example.my_flutter_app;


import android.os.Build;
import android.os.Bundle;
import android.widget.Toast;
import android.window.SplashScreenView;

import androidx.annotation.Nullable;
import androidx.core.view.WindowCompat;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.BasicMessageChannel;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.StandardMessageCodec;

public class MainActivity extends FlutterActivity {
    private static final String CHANNEL = "FtoO";

    private static final String CHANNEL2 = "OtoF";
    EventChannel.EventSink mEventSink;

    private static final String APPID = "WW1e933be11645237c";
    private static final String AGENTID = "1000012";
    private static final String SCHEMA = "wwauth1e933be11645237c000012";
int stringId;
//    IWWAPI iwwapi;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        WindowCompat.setDecorFitsSystemWindows(getWindow(), false);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            // Disable the Android splash screen fade out animation to avoid
            // a flicker before the similar frame is drawn in Flutter.
            getSplashScreen()
                    .setOnExitAnimationListener(
                            (SplashScreenView splashScreenView) -> {
                                splashScreenView.remove();
                            });
        }
        super.onCreate(savedInstanceState);
    }

    @Override
    public void configureFlutterEngine(FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);

//        iwwapi = WWAPIFactory.createWWAPI(this);
////        iwwapi.registerApp(SCHEMA);
//        stringId = getApplicationInfo().labelRes;


        MethodChannel channel = new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL2);
        new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
                .setMethodCallHandler((call, result) -> {
                    if ("sendO".equals(call.method)) {
                        result.success("Android " + android.os.Build.VERSION.RELEASE);


                        new Timer().schedule(new TimerTask() {
                            @Override
                            public void run() {
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Map<String,String> map = new HashMap<>();
                                        map.put("a","100");
                                        channel.invokeMethod("timer", map);
                                    }
                                });

                            }
                        } ,3000);

                    } else {
                        result.notImplemented();
                    }
                });

        new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), "Weixin")
                .setMethodCallHandler((call, result) -> {
                    if ("sendO".equals(call.method)) {

//                        WWMediaText txt = new WWMediaText("");
//                        txt.appPkg = getPackageName();
//                        txt.appName = getString(stringId);
//                        txt.appId = APPID;
//                        txt.agentId = AGENTID;
//
//                        WWAuthMessage.Req req = new WWAuthMessage.Req();
//                        req.sch = SCHEMA;
//                        req.appId = APPID;
//                        req.agentId = AGENTID;
//                        req.state = "dd";
//
//                        iwwapi.sendMessage(txt, new IWWAPIEventHandler() {
//                            @Override
//                            public void handleResp(BaseMessage resp) {
//                                if (resp instanceof WWAuthMessage.Resp) {
//                                    WWAuthMessage.Resp rsp = (WWAuthMessage.Resp) resp;
//                                    if (rsp.errCode == WWAuthMessage.ERR_CANCEL) {
//                                        Toast.makeText(MainActivity.this, "登录取消", Toast.LENGTH_SHORT).show();
//                                    }else if (rsp.errCode == WWAuthMessage.ERR_FAIL) {
//                                        Toast.makeText(MainActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
//                                    } else if (rsp.errCode == WWAuthMessage.ERR_OK) {
//                                        Toast.makeText(MainActivity.this, "登录成功：" + rsp.code,
//                                                Toast.LENGTH_SHORT).show();
//                                    }
//                                    result.success("WeiXin " + rsp.errCode);
//                                }
//                            }
//                        });



                    } else {
                        result.notImplemented();
                    }
                });

        BasicMessageChannel<Object> basicMessageChannel = new BasicMessageChannel<Object>(getFlutterEngine().getDartExecutor().getBinaryMessenger(), "BasicMessageChannel", StandardMessageCodec.INSTANCE);
//        BasicMessageChannel basicMessageChannel = new BasicMessageChannel(messager, "com.flutter.guide.MyFlutterView", new StandardMessageCodec());\

        basicMessageChannel.setMessageHandler(new BasicMessageChannel.MessageHandler<Object>() {
            @Override
            public void onMessage(Object o, BasicMessageChannel.Reply<Object> reply) {
                Toast.makeText(MainActivity.this,o.toString(),Toast.LENGTH_SHORT).show();
                //被动回复 flutter 消息
                reply.reply("I get it");

                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                basicMessageChannel.send("basicMessageChannel send");
                            }
                        });

                    }
                } ,3000);
                //主动给 flutter 发消息

            }
        });

        EventChannel mEventChannel = new EventChannel(
                getFlutterEngine().getDartExecutor(),
                "EventChannel");

        mEventChannel.setStreamHandler(new EventChannel.StreamHandler() {
            /**
             * 事件流建立成功会回调该方法
             * @param arguments
             * @param events
             */
            @Override
            public void onListen(Object arguments, EventChannel.EventSink events) {
                mEventSink = events;
                Toast.makeText(MainActivity.this,"事件流建立成功",Toast.LENGTH_SHORT);
            }

            @Override
            public void onCancel(Object arguments) {
                mEventSink = null;
            }
        });

        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(mEventSink!=null) {
                            mEventSink.success(System.currentTimeMillis() + "");
                        }
                    }
                });

            }
        } ,1000,1000);
    }
}
